package com.zjff.show.zjffshow;

import com.zjff.show.zjffshow.entity.ResultDao;
import com.zjff.show.zjffshow.tool.JSONTool;
import com.zjff.show.zjffshow.tool.UserAuth;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/*
    拦截器,拦截的是HTTP请求
 */
public class APIInterceptions implements HandlerInterceptor {
    @Override
    //前端请求时,return False 表示不允许访问控制器,return True 表示可以访问控制器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
//       String AccessKey = request.getHeader("AccessKey");
//        String AccessSecret = request.getHeader("AccessSecret");
//        UserAuth userAuth = new UserAuth();
//
//        if (userAuth.IsAuth(AccessKey,AccessSecret)){
//            flag = true;
//        }else {
//            outputResult(response);
//        }
//        System.out.println("preHandle拦截器启动");
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("postHandle拦截器启动");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        System.out.println("afterCompletion拦截器启动");
    }
    public void outputResult(HttpServletResponse response){//当key或secret不对时 输出
        try {
            PrintWriter out = null;
            ResultDao resultDao = new ResultDao();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            out = response.getWriter();
            resultDao.setCode("1");
            resultDao.setMsg("请求被拦截,原因:key或Secret错误！");
            out.println(JSONTool.getJsonTool().toJson(resultDao));//转换为JSON并输出
        }catch (Exception e){
            System.out.println("拦截器输出错误！"+e.getMessage());
        }
    }

}
